<?php
class MerchandiseList
{
	// Public variables to be read from Smarty template
	public $mPage = 1;
	public $mrTotalPages;
	public $mLinkToNextPage;
	public $mLinkToPreviousPage;
	public $mMerchandising;  
    public $mSelectedGenre;
    public $mSelectedCategory;
    
    // Define the template file to display when not browsing
    public $mContentsCell = 'shop_first_page.tpl';
	
	// Private members
	private $_mGenreId;
	private $_mCategoryId;
	
	public function __construct()
	{
		if (isset($_GET['GenreId']))
			$this->_mGenreId = $_GET['GenreId'];
		if (isset($_GET['CategoryId']))
			$this->_mCategoryId = $_GET['CategoryId'];
        if (isset($_SESSION['link_to_continue_shopping']))
        {
            $continue_shopping = Link::QueryStringToArray($_SESSION['link_to_continue_shopping']);
            
            if (array_key_exists('GenreId', $continue_shopping))
                $this->mSelectedGenre = (int)$continue_shopping['GenreId'];
            if (array_key_exists('CategoryId', $continue_shopping))
                $this->mSelectedCategory = (int)$continue_shopping['CategoryId'];
        }  
		// Get Page number from query string casting it to int
		if (isset($_GET['Page']))
			$this->mPage = (int)$_GET['Page'];   
            
		if ($this->mPage < 1)
			trigger_error('Invalid page number');
	}
	
	public function init()
	{                                         
		if (isset($this->_mGenreId))
		{                                                        
			$this->mMerchandising = Catalog::GetMerchandiseByGenre($this->_mGenreId, $this->mPage, $this->mrTotalPages);
		}
		elseif (isset($this->_mCategoryId))
		{
			$this->mMerchandising = Catalog::GetMerchandiseByCategory($this->_mCategoryId, $this->mPage, $this->mrTotalPages);
		}	                                                 
		// If there are subpages of products, display navigation controls   
		if ($this->mrTotalPages > 1)
		{
			// Build the Next link
			if ($this->mPage < $this->mrTotalPages)
			{
				if (isset($this->_mGenreId))
					$this->mLinkToNextPage = Link::ToGenre($this->_mGenreId, $this->mPage + 1);
				elseif (isset($this->_mCategoryId))
					$this->mLinkToNextPage = Link::ToCategory($this->_mCategoryId, $this->mPage + 1);
			}
			
			// Build the Previous link
			if ($this->mPage > 1)
			{
				if (isset($this->_mGenreId))
					$this->mLinkToPreviousPage = Link::ToGenre($this->_mGenreId, $this->mPage - 1);
				elseif (isset($this->_mCategoryId))
					$this->mLinkToPreviousPage = Link::ToCategory($this->_mCategoryId, $this->mPage - 1);
			}
		}
		for ($i = 0;$i < count($this->mMerchandising);$i++)
			$this->mMerchandising[$i]['link_to_merchandise'] = Link::ToMerchandise($this->mMerchandising[$i]['merchandise_id']);
	}
}
?>